<template>
  <div class="login-container">
    <div class="login-card">
      <!-- 左侧logo区域 -->
      <div class="logo-section">
        <div class="logo">
          <img src="@/assets/images/LOGO1.png" alt="Moolio Logo" class="logo-image" />
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="form-section">
        <div class="welcome-text">
          {{ isRegisterMode ? '创建新用户' : '欢迎来到' }}
          <div class="logo" v-if="!isRegisterMode">
            <img src="@/assets/images/LOGO2.png" alt="Moolio Logo" class="logo-image" />
          </div>
          {{ isRegisterMode ? '' : '平台' }}
        </div>

        <form class="login-form" @submit.prevent="handleSubmit">
          <div class="input-group">
            <input
              type="text"
              v-model="formData.username"
              placeholder="用户名/邮箱"
              class="form-input"
              :class="{ error: errors.username }"
              @input="clearError('username')"
            />
            <div class="error-message" v-if="errors.username">{{ errors.username }}</div>
          </div>

          <div class="input-group">
            <input
              type="password"
              v-model="formData.password"
              placeholder="密码"
              class="form-input"
              :class="{ error: errors.password }"
              @input="clearError('password')"
            />
            <div class="error-message" v-if="errors.password">{{ errors.password }}</div>
          </div>

          <div class="form-options" v-if="!isRegisterMode">
            <label class="checkbox-label">
              <input type="checkbox" v-model="formData.rememberMe" />
              <span class="checkbox-custom"></span>
              下次自动登录
            </label>
            <a href="#" class="forgot-password">忘记密码</a>
          </div>

          <div class="form-options agreement-section" v-if="isRegisterMode">
            <label class="checkbox-label">
              <input type="checkbox" v-model="formData.agreeTerms" />
              <span class="checkbox-custom"></span>
              我已阅读并接受
              <a href="#" class="agreement-link">用户协议</a>
              和
              <a href="#" class="agreement-link">隐私政策</a>
            </label>
          </div>

          <button type="submit" class="login-button" :disabled="isLoading">
            <span v-if="isLoading">{{ isRegisterMode ? '注册中...' : '登录中...' }}</span>
            <span v-else>{{ isRegisterMode ? '注册' : '登录' }}</span>
          </button>

          <div class="register-link">
            {{ isRegisterMode ? '已经是会员？' : '您还没有账户？' }}
            <a href="#" class="register-text" @click.prevent="toggleMode">
              {{ isRegisterMode ? '去登录' : '去注册' }}
            </a>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { apiService, ApiService } from '@/utils/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const isRegisterMode = ref(false)
const isLoading = ref(false)

const formData = ref({
  username: '',
  password: '',
  phone: '',
  confirmPassword: '',
  rememberMe: false,
  agreeTerms: false,
})

const errors = ref({
  username: '',
  password: '',
  phone: '',
  confirmPassword: '',
})

const login = async () => {
  if (!validateForm()) {
    return
  }

  isLoading.value = true

  try {
    if (isRegisterMode.value) {
      console.log('注册')

      // 检查用户名是否已存在
      const res = await apiService.getFilterRows({
        worksheetId: ApiService.WORKSHEETENUM.USER,
        filters: [
          {
            controlId: '68a7d3230372283d1e9247e3',
            dataType: 2,
            spliceType: 1,
            filterType: 2,
            value: formData.value.username,
          },
        ],
      })

      const isSuccess = Array.isArray(res.rows) && res.rows.length > 0

      if (isSuccess) {
        isLoading.value = false
        console.log('该用户名已被注册，请重新输入用户名')
        ElMessage.error('该用户名已被注册，请重新输入用户名')
      } else {
        console.log('该用户名未被注册，可以注册')
        // await apiService.register({
        //   worksheetId: ApiService.WORKSHEETENUM.USER,
        //   triggerWorkflow: true,
        //   controls: [
        //     {
        //       controlId: '68a7d3230372283d1e9247e3',
        //       value: formData.value.username,
        //     },
        //     {
        //       controlId: '68a7d3230372283d1e9247e4',
        //       value: formData.value.password,
        //     },
        //     {
        //       controlId: 'ctime',
        //       value: new Date(),
        //     },
        //   ],
        // })
        const registerRes = await apiService.registerUser({
          username: formData.value.username,
          password: formData.value.password,
        })

        console.log('注册成功，用户信息:', registerRes)

        // 保存用户信息和rowid到全局状态
        userStore.login(registerRes.data, registerRes.data.rowid)

        // 保存"记住我"状态到localStorage
        if (formData.value.rememberMe) {
          localStorage.setItem('rememberMe', 'true')
          localStorage.setItem('username', formData.value.username)
        }

        // 关闭加载状态
        isLoading.value = false

        // 显示成功提示
        ElMessage.success('注册成功')

        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          // 注册成功后默认跳转到项目列表页面，因为注册后权限默认是客户
          router.push('/tabs/project')
        }, 1500)
      }
    } else {
      console.log('登录')
      const res = await apiService.getFilterRows({
        worksheetId: ApiService.WORKSHEETENUM.USER,
        filters: [
          {
            controlId: '68a7d3230372283d1e9247e3',
            dataType: 2,
            spliceType: 1,
            filterType: 2,
            value: formData.value.username,
          },
          {
            controlId: '68a7d3230372283d1e9247e4',
            dataType: 2,
            spliceType: 1,
            filterType: 2,
            value: formData.value.password,
          },
        ],
      })

      const isSuccess = Array.isArray(res.rows) && res.rows.length > 0

      if (isSuccess) {
        const userRowid = res.rows[0]['rowid']
        const userInfo = res.rows[0]

        console.log('userInfo:', userInfo)

        const companyRowid = userInfo['68b908278326c4bbc62dfa28'] && JSON.parse(userInfo['68b908278326c4bbc62dfa28']).length > 0 
          ? JSON.parse(JSON.parse(userInfo['68b908278326c4bbc62dfa28'])[0]['sourcevalue'])['rowid']
          : null

        console.log('companyRowid:', companyRowid)

        const setUserInfo = {
          username: userInfo['68a7d3230372283d1e9247e3'],
          companyRowid: companyRowid,
          permissions: userInfo['68ae606e3f18dc08c56c5d64'],
          rowid: userRowid,
        }

        console.log('登录成功，用户rowid:', userRowid)
        console.log('用户信息:', userInfo)

        // 保存用户信息和rowid到全局状态
        userStore.login(setUserInfo, userRowid)

        console.log('userStore.company:', userStore.company)

        // 保存"记住我"状态到localStorage
        if (formData.value.rememberMe) {
          localStorage.setItem('rememberMe', 'true')
          localStorage.setItem('username', formData.value.username)
        } else {
          localStorage.removeItem('rememberMe')
          localStorage.removeItem('username')
        }

        // 关闭加载状态
        isLoading.value = false

        // 显示成功提示
        ElMessage.success('登录成功')

        // 根据用户权限跳转到不同页面
        setTimeout(() => {
          if (setUserInfo.permissions === '客户') {
            router.push('/tabs/project')
          } else if (setUserInfo.permissions === '平台') {
            router.push('/tabs/project')
          } else {
            // 默认跳转到项目列表页面
            router.push('/tabs/project')
          }
        }, 1500)
      } else {
        isLoading.value = false
        ElMessage.error('用户名或密码错误')
      }
    }
  } catch (error) {
    isLoading.value = false
    console.error('登录/注册失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

const clearError = (field) => {
  if (errors.value[field]) {
    errors.value[field] = ''
  }
}

const setErrorWithTimer = (field, message) => {
  errors.value[field] = message
  // 3秒后自动清除错误信息
  setTimeout(() => {
    if (errors.value[field] === message) {
      errors.value[field] = ''
    }
  }, 3000)
}

const validateForm = () => {
  // 先清除所有错误
  errors.value = {
    username: '',
    password: '',
    phone: '',
    confirmPassword: '',
  }

  let isValid = true

  if (!formData.value.username.trim()) {
    setErrorWithTimer('username', '请输入用户名')
    isValid = false
  }

  if (isRegisterMode.value) {
    if (!formData.value.password.trim()) {
      setErrorWithTimer('password', '请输入密码')
      isValid = false
    } else if (formData.value.password.length < 6) {
      setErrorWithTimer('password', '密码长度至少为6位')
      isValid = false
    } else if (!/[a-zA-Z]/.test(formData.value.password)) {
      setErrorWithTimer('password', '密码必须包含字母')
      isValid = false
    }

    if (!formData.value.agreeTerms) {
      ElMessage.warning('请阅读并接受用户协议和隐私政策')
      isValid = false
    }
  } else {
    if (!formData.value.password.trim()) {
      setErrorWithTimer('password', '请输入密码')
      isValid = false
    }
  }

  return isValid
}

const handleSubmit = () => {
  login()
}

const toggleMode = () => {
  isRegisterMode.value = !isRegisterMode.value
  // 清除错误信息
  errors.value = {
    username: '',
    password: '',
    phone: '',
    confirmPassword: '',
  }
  // 重置表单
  formData.value = {
    username: '',
    password: '',
    phone: '',
    confirmPassword: '',
    rememberMe: false,
    agreeTerms: false,
  }
}

// 初始化时检查是否有记住的登录信息
const initRememberMe = () => {
  const rememberMe = localStorage.getItem('rememberMe')
  const savedUsername = localStorage.getItem('username')

  if (rememberMe === 'true' && savedUsername) {
    formData.value.username = savedUsername
    formData.value.rememberMe = true
  }
}

// 页面加载时初始化
initRememberMe()
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background-image: url('@/assets/images/background.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.login-card {
  background: rgba(255, 255, 255, 0.6);
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 100%;
  max-width: 900px;
  min-height: 500px;
  display: flex;
}

.logo-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.logo {
  text-align: center;
}

.logo-image {
  max-width: 300px;
  max-height: 150px;
  margin-right: -60px;
  width: auto;
  height: auto;
}

.form-section {
  flex: 1;
  padding: 8%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
}

.form-section::before {
  content: '';
  position: absolute;
  top: 30px;
  left: 30px;
  right: 30px;
  bottom: 30px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.form-section > * {
  position: relative;
  z-index: 2;
}

.welcome-text {
  font-weight: 800;
  font-size: 20px;
  color: #333;
  margin-bottom: 40px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.welcome-text .logo {
  display: inline-flex;
  align-items: center;
}

.welcome-text .logo-image {
  height: 24px;
  width: auto;
  max-width: 120px;
  margin-right: 0 !important; /* 确保覆盖通用样式 */
}

.login-form {
  width: 100%;
}

.input-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  padding: 15px 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #999999;
  background-color: #f4f4f4;
  outline: none;
}

.form-input::placeholder {
  color: #999;
}

.form-input.error {
  border-color: #f070b0;
}

.error-message {
  color: #f070b0;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 5px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  font-size: 14px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #666;
}

.checkbox-label input[type='checkbox'] {
  display: none;
}

.checkbox-custom {
  width: 16px;
  height: 16px;
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s;
}

.checkbox-label input[type='checkbox']:checked + .checkbox-custom {
  background: #eb4196;
  border-color: #eb4196;
}

.checkbox-label input[type='checkbox']:checked + .checkbox-custom::after {
  content: '✓';
  position: absolute;
  color: white;
  font-size: 12px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.forgot-password {
  color: #333;
  text-decoration: underline;
  font-size: 14px;
}

.login-button {
  width: 100%;
  background: #eb4196;
  color: white;
  border: none;
  padding: 15px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 20px;
}

.login-button:hover:not(:disabled) {
  background: #d63384;
}

.login-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-text {
  color: #eb4196;
  text-decoration: underline;
  margin-left: 5px;
}

.register-text:hover {
  text-decoration: underline;
}

.agreement-section {
  justify-content: flex-start;
  flex-wrap: wrap;
}

.agreement-section .checkbox-label {
  line-height: 1.4;
}

.agreement-link {
  color: #666;
  text-decoration: none;
  margin: 0 2px;
}

.agreement-link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    flex-direction: column;
    max-width: 400px;
  }

  .logo-section {
    padding: 30px 20px;
  }

  .logo-image {
    max-width: 150px;
    max-height: 100px;
  }

  .form-section {
    padding: 30px 20px;
  }

  .form-section::before {
    top: 15px;
    left: 15px;
    right: 15px;
    bottom: 15px;
    border-radius: 12px;
  }

  .welcome-text {
    font-size: 18px;
    margin-bottom: 30px;
  }
}
</style>
